package org.tuling.tlmallusersentineldemo.exception;

import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.tuling.tlmallcommon.Result;

/**
 * @author: Fox
 * @Desc:
 **/
public class ExceptionUtil {

    public static SentinelClientHttpResponse handleBlockException(HttpRequest request,
                                                                  byte[] body, ClientHttpRequestExecution execution, BlockException ex) {

        Result result = Result.failed("===被限流啦===");
        try {
            return new SentinelClientHttpResponse(new ObjectMapper().writeValueAsString(result));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static SentinelClientHttpResponse handleFallback(HttpRequest request,
                                                            byte[] body, ClientHttpRequestExecution execution, BlockException ex) {
        Result result = Result.failed("===被异常降级啦===");
        try {
            return new SentinelClientHttpResponse(new ObjectMapper().writeValueAsString(result));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
